package restaurant.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import restaurant.pojo.Board;
import restaurant.pojo.DivPage;
import restaurant.pojo.Foods;
import restaurant.pojo.FoodsType;
import restaurant.service.FoodService;
import restaurant.service.impl.FoodServiceImpl;
import restaurant.utils.BaseServlet;

/**
 * Servlet implementation class BaseFoodsServlet
 */
@WebServlet("/restaurant/detail/BaseFoodsServlet")
public class BaseFoodsServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private FoodService service = new FoodServiceImpl();
		public String showFoods(HttpServletRequest req,HttpServletResponse resp) {
			
			String pageNum = req.getParameter("pageNum");
			String pageSize = req.getParameter("pageSize");
			try {
				DivPage<Foods> divPage = service.showFood(pageNum, pageSize);
				req.setAttribute("divPage", divPage);
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "foodList.jsp";
		}
		
	public String addFoods(HttpServletRequest req, HttpServletResponse resp) {
		try {
			service.addFood(req);
			return "BaseFoodsServlet?action=showFoods";
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	public String delFood(HttpServletRequest req, HttpServletResponse resp) {
		String id = req.getParameter("id");
		try {
			service.deleFood(id);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "BaseFoodsServlet?action=showFoods";
	}
	public String updateFood(HttpServletRequest req, HttpServletResponse resp) {
		try {
			service.updateFood(req);
			return "BaseFoodsServlet?action=showFoods";
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	public void getAllCuisine(HttpServletRequest req, HttpServletResponse resp) {
		resp.setContentType("application/json;charset=utf-8");
		try {
			List<FoodsType> types = service.getAllType();
			String jsonStr = JSON.toJSONString(types);
			resp.getWriter().println(jsonStr);
		} catch (SQLException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public String findFood(HttpServletRequest req,HttpServletResponse resp) {
		String param = req.getParameter("keyword");
		try {
			DivPage<Foods> divPage = new DivPage<Foods>();
			List<Foods> food = service.findFood(param);
			divPage.setDatas(food);
			req.setAttribute("divPage", divPage);
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		return "foodList.jsp";
	}
}
